package com.zhigh.project.security.test.web;

import com.zhigh.project.security.jcasbin.config.annotation.method.EnableJCasbinGlobalMethodSecurity;
import com.zhigh.project.security.jwt.web.configurers.JWTAuthorizationHeaderConfigurer;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import java.util.List;
import java.util.Optional;

@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
@EnableJCasbinGlobalMethodSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final Optional<List<AuthenticationProvider>> authenticationProviders;

    public WebSecurityConfiguration(Optional<List<AuthenticationProvider>> authenticationProviders) {
        this.authenticationProviders = authenticationProviders;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.apply(new JWTAuthorizationHeaderConfigurer<>());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        authenticationProviders.ifPresent(
                providers -> providers.forEach(auth::authenticationProvider)
        );

    }

}
